<script setup lang="ts">
import { h, reactive } from 'vue';
import { MeetingUser } from '../index.d';
import { Button } from '@nutui/nutui-taro';
import { Plus as AppNutIconPlus } from '@nutui/icons-vue-taro';
const emits = defineEmits<{
  (e: 'onChange', userList: MeetingUser[]): void;
}>();
const state: {
  /**
   * 参会用户选择弹窗是否显示
   */
  appUserListPopupIsShow: boolean;
  userList: MeetingUser[];
} = reactive({
  appUserListPopupIsShow: false,
  userList: [],
});

/**
 * 返回user在list中的index，如果没有找到返回：-1
 * @param user 需要查询的user
 */
function findUserIndex(user: AppSysUser.Dto) {
  const index = state.userList.findIndex((item) => {
    return item.uaaUserId === user.uaaUserId;
  });
  return index;
}
/**
 * 选择用户
 */
function addUser(user: AppSysUser.Dto) {
  //选择相同的人员跳过
  const index = findUserIndex(user);
  if (index >= 0) return;

  state.userList.push({
    uaaUserId: user.uaaUserId,
    username: user.name,
    deptName: user.organ,
    render: () => {
      return renderButton(user);
    },
  });
  emits('onChange', state.userList);
}
/**
 * 渲染button按钮
 * @param user 用户信息
 */
function renderButton(user: AppSysUser.Dto) {
  return h(
    Button,
    {
      plain: true,
      size: 'mini',
      type: 'danger',
      onClick: () => {
        deleteUser(user);
      },
    },
    () => '删除',
  );
}
/**
 * button按钮删除用户
 */
function deleteUser(user: AppSysUser.Dto) {
  const deleteIndex = findUserIndex(user);
  state.userList.splice(deleteIndex, 1);
  emits('onChange', state.userList);
}
</script>
<template>
  <nut-table
    class="meeting-edit-user-table"
    bordered
    striped
    :columns="[
      { title: '姓名', key: 'username', align: 'center' },
      { title: '部门', key: 'deptName', align: 'center' },
      { title: '操作', key: 'render', align: 'center' },
    ]"
    :data="state.userList"
  />
  <nut-button
    block
    plain
    shape="round"
    type="info"
    @click="state.appUserListPopupIsShow = !state.appUserListPopupIsShow"
  >
    <template #icon>
      <app-nut-icon-plus />
    </template>
    <text>参会人员</text>
  </nut-button>

  <app-user-list-popup
    v-model="state.appUserListPopupIsShow"
    title="参会人员"
    @on-selected="addUser"
  />
</template>
<style lang="scss">
.meeting-edit-user-table {
  margin-bottom: 20px;
}
</style>
